
/**
 * Dielectric
 * @version 1.0
 * @since 1.0
 * <p>
 * Created by Murphy at 2021/7/19 10:13
 **/
#include "Dielectric.hpp"
#include "usage/Hittable.hpp"
#include "math/Math.hpp"
namespace Stitches
{

bool Dielectric::scatter(const Ray &r_in, const HitRecord &rec,
                         Stitches::Vec3f &attenuation,
                         Stitches::Ray &scattered) const
{
    attenuation = Vec3f(1.0, 1.0, 1.0);
    //判断交点是在外部还是内部 front_face为true时-->外部
    double etai_over_etat = rec.front_face ? (1.0 / ref_idx) : ref_idx;
    Vec3f unit_direction = glm::normalize(r_in.direction());

    double cos_theta = fmin(dot(-unit_direction, rec.normal), 1.0);
    double sin_theta = sqrt(1.0 - cos_theta * cos_theta);

    if (etai_over_etat * sin_theta > 1.0)
    {
        //全内反射
        Vec3f reflected = reflect(unit_direction, rec.normal);
        scattered = Ray(rec.p, reflected);
        return true;
    }

    double reflect_prob = schlick(cos_theta, etai_over_etat);//反射率
    if (random_double() < reflect_prob) {
        Vec3f reflected = reflect(unit_direction, rec.normal);
        scattered = Ray(rec.p, reflected);
        return true;
    }

    Vec3f refracted = Stitches::refract(unit_direction, rec.normal, etai_over_etat);
    scattered = Ray(rec.p, refracted);
    return true;
}

}
